package person.learn.controller.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;
import person.learn.conf.http.HttpRequestHandler;
import person.learn.entity.Goods;
import person.learn.service.GoodsService;
import person.learn.util.Constant;
import person.learn.util.JsonResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by barton on 16-1-29.
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private HttpRequestHandler handler;

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<JsonResponse<Page<Goods>>> page(HttpServletRequest request,
                                                          @PageableDefault(size = 10, page = 0,
                                                                  sort = {"id", "name"},
                                                                  direction = Sort.Direction.ASC)
                                                                  Pageable pageRequest) {

        Map<String, Object> searchParam = WebUtils.getParametersStartingWith(request, Constant
                .SEARCH_OPERTOR);

        return new ResponseEntity<>(new JsonResponse<>(this.goodsService.findAllPage(searchParam,
                pageRequest)), HttpStatus.OK);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<JsonResponse<Goods>> findOneById(@PathVariable Long id) {
        return new ResponseEntity<>(new JsonResponse<>(this.goodsService.findOne(id)), HttpStatus
                .OK);
    }

    /**
     * 测试
     *
     * @return
     */
    @RequestMapping(value = "/toFruit", method = RequestMethod.GET)
    public String toFruit() {
        ResponseEntity<Object> re = handler.get("http://localhost:8081/v1/fruits");
        System.out.println(re.getStatusCode());
        System.out.println(re.getBody());
        System.out.println(re.getHeaders());
        return "fruit";
    }
}
